package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.GenericArrayType;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {
        TurnoverReportVO tr = new TurnoverReportVO();
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        Map<String, Object> map = new HashMap<>();
        tr.setDateList(StringUtils.join(dateList, ","));
        for (LocalDate localDate : dateList) {
            map.put("begin", LocalDateTime.of(localDate,LocalTime.MIN));
            map.put("end", LocalDateTime.of(localDate,LocalTime.MAX));
            map.put("status", Orders.COMPLETED);
            Double count = reportMapper.getCountByOrder(map);
            count = count == null ? 0.0 : count;
            turnoverList.add(count);
        }
        tr.setTurnoverList(StringUtils.join(turnoverList,","));
        return tr;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        Map<String, Object> map = new HashMap<>();
        userReportVO.setDateList(StringUtils.join(dateList, ","));
        for (LocalDate localDate : dateList) {
            map.put("end", LocalDateTime.of(localDate,LocalTime.MAX));
            Integer totalCount = reportMapper.getUserCount(map);
            map.put("begin", LocalDateTime.of(localDate,LocalTime.MIN));
            Integer newCount = reportMapper.getUserCount(map);
            totalUserList.add(totalCount);
            newUserList.add(newCount);
        }
        userReportVO.setTotalUserList(StringUtils.join(totalUserList,","));
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        OrderReportVO userReportVO = new OrderReportVO();
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        userReportVO.setDateList(StringUtils.join(dateList, ","));
        for (LocalDate localDate : dateList) {
            Integer orderCount = reportMapper.getOrderCount(getOrderMap(localDate,null));
            Integer validOrderCount = reportMapper.getValidOrderCount(getOrderMap(localDate,Orders.COMPLETED));
            orderCountList.add(orderCount == null ? 0 : orderCount);
            validOrderCountList.add(validOrderCount == null ? 0 : validOrderCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Integer orderCompletionRate = totalOrderCount == 0 ? 0 : validOrderCount/totalOrderCount;
        Double orderRate = orderCompletionRate.doubleValue();
        userReportVO.setOrderCountList(StringUtils.join(orderCountList,","));
        userReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList,","));
        userReportVO.setTotalOrderCount(totalOrderCount);
        userReportVO.setValidOrderCount(validOrderCount);
        userReportVO.setOrderCompletionRate(orderRate);
        return userReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        Map<String, Object> map = new HashMap<>();
        map.put("begin",LocalDateTime.of(begin, LocalTime.MIN));
        map.put("end",LocalDateTime.of(begin, LocalTime.MIN));
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> list = reportMapper.getTop10(map);
        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));
        return salesTop10ReportVO;
    }

    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        //查询概览数据
        LocalDateTime endTime = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MIN);
        LocalDateTime startTime = LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.MIN);
        BusinessDataVO businessData = workspaceService.getBusinessData(startTime, endTime);
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template\\运营数据报表模板.xlsx");
        if (is != null){
            XSSFWorkbook sheets = new XSSFWorkbook(is);
            XSSFSheet sheetAt = sheets.getSheet("Sheet1");
            sheetAt.getRow(1).getCell(1).setCellValue(startTime.getYear()+"年"+startTime.getMonthValue()+"月"+startTime.getDayOfMonth()+"日-"
                    +endTime.getYear()+"年"+endTime.getMonthValue()+"月"+endTime.getDayOfMonth()+"日"
            );
            XSSFRow row = sheetAt.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate()+"%");
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheetAt.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //营业数据
            LocalDate begin = LocalDate.now().minusDays(30);
            for (int i = 0; i < 30; i++) {
                LocalDateTime start = LocalDateTime.of(begin, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(begin, LocalTime.MAX);
                BusinessDataVO bs = workspaceService.getBusinessData(start, end);
                row = sheetAt.getRow(i + 7);
                row.getCell(1).setCellValue(start+"-"+end);
                row.getCell(2).setCellValue(bs.getTurnover());
                row.getCell(3).setCellValue(bs.getValidOrderCount());
                row.getCell(4).setCellValue(bs.getOrderCompletionRate());
                row.getCell(5).setCellValue(bs.getUnitPrice());
                row.getCell(6).setCellValue(bs.getNewUsers());
                begin = begin.plusDays(1);
            }
            ServletOutputStream os = response.getOutputStream();
            sheets.write(os);
            os.close();
            sheets.close();
        }
    }

    public Map<String,Object> getOrderMap(LocalDate localDate, Integer status){
        Map<String, Object> map = new HashMap<>();
        if (localDate != null){
            map.put("begin", LocalDateTime.of(localDate,LocalTime.MIN));
            map.put("end", LocalDateTime.of(localDate,LocalTime.MAX));
        }
        if (status != null){
            map.put("status", status);
        }
        return map;
    }
}
